package com.lexue.articlesync.controller;

import com.lexue.articlesync.entity.Video;
import com.lexue.articlesync.repository.VideoRepository;
import com.lexue.articlesync.service.ContentSyncService;
import com.lexue.articlesync.service.FileUploadService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 视频管理API控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/videos")
@RequiredArgsConstructor
public class VideoController {
    
    private final VideoRepository videoRepository;
    private final FileUploadService fileUploadService;
    private final ContentSyncService contentSyncService;
    
    /**
     * 获取视频列表
     */
    @GetMapping
    public ResponseEntity<Page<Video>> getVideos(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "createdAt") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir) {
        
        Sort sort = sortDir.equalsIgnoreCase("desc") ? 
                Sort.by(sortBy).descending() : Sort.by(sortBy).ascending();
        
        Pageable pageable = PageRequest.of(page, size, sort);
        Page<Video> videos = videoRepository.findAll(pageable);
        
        return ResponseEntity.ok(videos);
    }
    
    /**
     * 根据ID获取视频
     */
    @GetMapping("/{id}")
    public ResponseEntity<Video> getVideo(@PathVariable Long id) {
        Optional<Video> video = videoRepository.findById(id);
        return video.map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 搜索视频
     */
    @GetMapping("/search")
    public ResponseEntity<List<Video>> searchVideos(
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String tag,
            @RequestParam(required = false) String status) {
        
        List<Video> videos;
        
        if (title != null && !title.trim().isEmpty()) {
            videos = videoRepository.findByTitleContainingIgnoreCase(title);
        } else if (tag != null && !tag.trim().isEmpty()) {
            videos = videoRepository.findByTagsContaining(tag);
        } else if (status != null && !status.trim().isEmpty()) {
            try {
                Video.VideoStatus videoStatus = Video.VideoStatus.valueOf(status.toUpperCase());
                videos = videoRepository.findByStatus(videoStatus);
            } catch (IllegalArgumentException e) {
                return ResponseEntity.badRequest().build();
            }
        } else {
            videos = videoRepository.findTop10ByOrderByCreatedAtDesc();
        }
        
        return ResponseEntity.ok(videos);
    }
    
    /**
     * 上传视频文件
     */
    @PostMapping("/upload")
    public ResponseEntity<Video> uploadVideo(
            @RequestParam("file") MultipartFile file,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String description,
            @RequestParam(required = false) String tags,
            @RequestParam(defaultValue = "true") Boolean isOriginal,
            @RequestParam(defaultValue = "false") Boolean joinActivity) {
        
        try {
            Video video = fileUploadService.uploadVideoFile(file, title, description, tags, isOriginal, joinActivity);
            Video savedVideo = videoRepository.save(video);
            
            log.info("视频上传成功: {}", savedVideo.getId());
            return ResponseEntity.ok(savedVideo);
            
        } catch (Exception e) {
            log.error("视频上传失败", e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 创建视频记录
     */
    @PostMapping
    public ResponseEntity<Video> createVideo(@RequestBody VideoRequest request) {
        try {
            Video video = Video.builder()
                    .title(request.getTitle())
                    .description(request.getDescription())
                    .filePath(request.getFilePath())
                    .fileName(request.getFileName())
                    .fileSize(request.getFileSize())
                    .duration(request.getDuration())
                    .format(request.getFormat())
                    .coverImage(request.getCoverImage())
                    .thumbnail(request.getThumbnail())
                    .tags(request.getTags())
                    .isOriginal(request.getIsOriginal() != null ? request.getIsOriginal() : true)
                    .joinActivity(request.getJoinActivity() != null ? request.getJoinActivity() : false)
                    .activityId(request.getActivityId())
                    .scheduledTime(request.getScheduledTime())
                    .status(Video.VideoStatus.DRAFT)
                    .build();
            
            Video savedVideo = videoRepository.save(video);
            
            // 如果指定了平台，创建发布配置
            if (request.getPlatformIds() != null && !request.getPlatformIds().isEmpty()) {
                contentSyncService.createVideoPublishConfigs(savedVideo, request.getPlatformIds());
            }
            
            log.info("视频创建成功: {}", savedVideo.getId());
            return ResponseEntity.ok(savedVideo);
            
        } catch (Exception e) {
            log.error("视频创建失败", e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 更新视频
     */
    @PutMapping("/{id}")
    public ResponseEntity<Video> updateVideo(@PathVariable Long id, @RequestBody VideoRequest request) {
        Optional<Video> optionalVideo = videoRepository.findById(id);
        if (!optionalVideo.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        try {
            Video video = optionalVideo.get();
            video.setTitle(request.getTitle());
            video.setDescription(request.getDescription());
            video.setCoverImage(request.getCoverImage());
            video.setThumbnail(request.getThumbnail());
            video.setTags(request.getTags());
            video.setIsOriginal(request.getIsOriginal() != null ? request.getIsOriginal() : video.getIsOriginal());
            video.setJoinActivity(request.getJoinActivity() != null ? request.getJoinActivity() : video.getJoinActivity());
            video.setActivityId(request.getActivityId());
            video.setScheduledTime(request.getScheduledTime());
            
            if (request.getDuration() != null) {
                video.setDuration(request.getDuration());
            }
            
            Video savedVideo = videoRepository.save(video);
            
            log.info("视频更新成功: {}", savedVideo.getId());
            return ResponseEntity.ok(savedVideo);
            
        } catch (Exception e) {
            log.error("视频更新失败", e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 删除视频
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteVideo(@PathVariable Long id) {
        Optional<Video> optionalVideo = videoRepository.findById(id);
        if (!optionalVideo.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        try {
            Video video = optionalVideo.get();
            
            // 删除视频文件
            if (video.getFilePath() != null) {
                fileUploadService.deleteFile(video.getFilePath());
            }
            
            videoRepository.deleteById(id);
            log.info("视频删除成功: {}", id);
            return ResponseEntity.ok().build();
            
        } catch (Exception e) {
            log.error("视频删除失败: {}", id, e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 发布视频到指定平台
     */
    @PostMapping("/{id}/publish")
    public ResponseEntity<String> publishVideo(
            @PathVariable Long id,
            @RequestParam(required = false) List<Long> platformIds) {
        
        Optional<Video> optionalVideo = videoRepository.findById(id);
        if (!optionalVideo.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        try {
            Video video = optionalVideo.get();
            
            // 如果指定了新的平台，创建发布配置
            if (platformIds != null && !platformIds.isEmpty()) {
                contentSyncService.createVideoPublishConfigs(video, platformIds);
            }
            
            // 异步发布
            contentSyncService.syncVideo(id);
            
            log.info("开始发布视频: {}", id);
            return ResponseEntity.ok("视频发布任务已启动");
            
        } catch (Exception e) {
            log.error("视频发布失败: {}", id, e);
            return ResponseEntity.badRequest().body("视频发布失败: " + e.getMessage());
        }
    }
    
    /**
     * 视频请求DTO
     */
    public static class VideoRequest {
        private String title;
        private String description;
        private String filePath;
        private String fileName;
        private Long fileSize;
        private Integer duration;
        private String format;
        private String coverImage;
        private String thumbnail;
        private String tags;
        private Boolean isOriginal;
        private Boolean joinActivity;
        private String activityId;
        private LocalDateTime scheduledTime;
        private List<Long> platformIds;
        
        // Getters and Setters
        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }
        
        public String getDescription() { return description; }
        public void setDescription(String description) { this.description = description; }
        
        public String getFilePath() { return filePath; }
        public void setFilePath(String filePath) { this.filePath = filePath; }
        
        public String getFileName() { return fileName; }
        public void setFileName(String fileName) { this.fileName = fileName; }
        
        public Long getFileSize() { return fileSize; }
        public void setFileSize(Long fileSize) { this.fileSize = fileSize; }
        
        public Integer getDuration() { return duration; }
        public void setDuration(Integer duration) { this.duration = duration; }
        
        public String getFormat() { return format; }
        public void setFormat(String format) { this.format = format; }
        
        public String getCoverImage() { return coverImage; }
        public void setCoverImage(String coverImage) { this.coverImage = coverImage; }
        
        public String getThumbnail() { return thumbnail; }
        public void setThumbnail(String thumbnail) { this.thumbnail = thumbnail; }
        
        public String getTags() { return tags; }
        public void setTags(String tags) { this.tags = tags; }
        
        public Boolean getIsOriginal() { return isOriginal; }
        public void setIsOriginal(Boolean isOriginal) { this.isOriginal = isOriginal; }
        
        public Boolean getJoinActivity() { return joinActivity; }
        public void setJoinActivity(Boolean joinActivity) { this.joinActivity = joinActivity; }
        
        public String getActivityId() { return activityId; }
        public void setActivityId(String activityId) { this.activityId = activityId; }
        
        public LocalDateTime getScheduledTime() { return scheduledTime; }
        public void setScheduledTime(LocalDateTime scheduledTime) { this.scheduledTime = scheduledTime; }
        
        public List<Long> getPlatformIds() { return platformIds; }
        public void setPlatformIds(List<Long> platformIds) { this.platformIds = platformIds; }
    }
}